<?php

namespace App\Service;

use App\Models\EwDics;
use App\Util\Fun;

class DicsService extends BaseService
{
	const DISPLAY_TRUE = 1;		//显示标识：是
	const DISPLAY_FALSE = 0;	//显示标识：否
	const DEL_TRUE = 1;			//删除标识：是
	const DEL_FALSE = 0;		//删除标识：否
	const SUBS_TRUE = 1;		//订阅标识：是
	const SUBS_FALSE = 0;		//订阅标识：否

	const CATE_AREA = -1;		//城市区域
	const CATE_UNIQUE = -2;		//城市特色
	const CATE_HOUSE_NEW = 1;   //新房
	const CATE_HOUSE_SECO = 2;  //二手房
	const CATE_HOUSE_RENT = 3;  //租房
	const CATE_HOUSE_OFFI = 4;  //写字楼
	const CATE_HOUSE_SHOP = 5;  //商铺

	public static function getList($params, $count = FALSE)
	{
		$query = EwDics::query();
		$query->columns(['id,name,pid,cate_id,is_multi,is_display,is_del']);

		$query->andWhere("is_del = " . self::DEL_FALSE);

		if (isset($params->is_display) && $params->is_display)
			$builder->andWhere("r.is_display = ". $params->is_display);

		//cate_id
		if (isset($params->cate_id) && $params->cate_id > 0)
			$query->andwhere("cate_id = :cate_id:")->bind(['cate_id' => $params->cate_id]);

		//pid
		if (isset($params->pid) && $params->pid > 0)
			$query->andwhere("pid = :pid:")->bind(['pid' => $params->pid]);

		//is_hot
		if (isset($params->is_hot))
			$query->andwhere("is_hot = :is_hot:")->bind(['is_hot' => $params->is_hot]);

		//name
		if (isset($params->name) && $params->name )
			$query->andwhere("name LIKE '%" . $params->name . "%'");


		//总条数
		if ($count)
			return $query->execute()->count();

		//order_by 排序
		if (isset($params->order_by)){
			$sql = parent::orderBy($params->order_by);
			$query->orderBy($sql);
		}

		//分页
		$query->limit($params->page_num,($params->p-1)*$params->page_num);

		return $query->execute();
	}

	/**
	 * [getearch description]
	 * @param  [type]  $params [description]
	 * @param  boolean $count  [description]
	 * @return [type]          [description]
	 */
	public static function getSearch($params, $count = FALSE)
	{
		$query = EwDics::query();
		$query->andWhere("is_del = " . self::DEL_FALSE);

		//获取城市列表
		if ($params->type == self::CATE_AREA){ //cate_id = -1
			$query->columns(['id,name,pid,is_hot,order_by,is_display']);
			$query->andWhere("cate_id = " .self::CATE_AREA );
			$params->cate_id = self::CATE_AREA;
		//获取城市特色列表
		}else if ($params->type == self::CATE_UNIQUE){//cate_id = -2
			$query->columns(['id,name,pid,order_by,is_display']);
			$query->andWhere("cate_id = " .self::CATE_UNIQUE );
			$params->cate_id = self::CATE_UNIQUE;
		}else{//获取字典列表
			$query->columns(['id,name,pid,is_subs,order_by,is_display']);
			$query->andWhere("cate_id >= 0" );
			$query->andwhere("cate_id = :cate_id:")->bind(['cate_id' => $params->cate_id]);
		}
		
		if (isset($params->is_display) && $params->is_display)
			$builder->andWhere("r.is_display = ". $params->is_display);

		//cate_id
		if (isset($params->cate_id) && $params->cate_id > 0)
			$query->andwhere("cate_id = :cate_id:")->bind(['cate_id' => $params->cate_id]);

		//pid
		if (isset($params->pid) && $params->pid > 0)
			$query->andwhere("pid = :pid:")->bind(['pid' => $params->pid]);

		//is_hot
		if (isset($params->is_hot))
			$query->andwhere("is_hot = :is_hot:")->bind(['is_hot' => $params->is_hot]);

		//name
		if (isset($params->name) && $params->name )
			$query->andwhere("name LIKE '%" . $params->name . "%'");

		//总条数
		if ($count)
			return $query->execute()->count();

		//order_by 排序
		if (isset($params->order_by)){
			$sql = parent::orderBy($params->order_by);
			$query->orderBy($sql);
		}

		//分页
		$query->limit($params->page_num,($params->p-1)*$params->page_num);

		return $query->execute();
	}

	public static function getInfo($id = 0, $cate = NULL)
	{
		if ($cate == self::CATE_AREA)
			return EwDics::findFirst(['columns' => 'id,name,pid,order_by,is_hot,is_display', 'conditions' => ' id = ' . $id]);
		
		if ($cate == self::CATE_UNIQUE)
			return EwDics::findFirst(['columns' => 'id,name,pid,order_by,is_display', 'conditions' => ' id = ' . $id]);

		return EwDics::findFirst($id);
	}

	public static function count()
	{
		return EwDics::count();
	}
    
    //树
    public static function getAllCtiy(){
        //dics_type='region'
        $sql = "SELECT id,name,pid FROM `ew_dics` WHERE dics_type='region' AND is_display=1 AND is_del=0";
        $data = (new Fun)->db_execute($sql);
        $tree = (new Fun)->genTree($data);
        return $tree;
    }

	/**
	 * [getTree 获取树形结构 房源及订阅筛选条件]
	 * @param  integer $cate_id [cats外键]
	 * @return [type]           [description]
	 */
	public static function getTree($params)
	{
		$table_id = HouseService::getTableId();
		//默认获取房源类型第一条 二手房
		$arr = CatsService::getTableCats($table_id);
		$cate_id = current($arr) ? $arr[0]['id'] : NULL;
		$params->cate_id = (isset($params->cate_id) && ($params->cate_id)) ? $params->cate_id : $cate_id;

		$query = EwDics::query();
		$query->columns(['id,name,pid,IFNULL(dics_type,"other") AS dics_type']);

		$query->andWhere("is_del = " . self::DEL_FALSE);

		$query->andWhere("is_display = " . self::DISPLAY_TRUE);

		

		if (isset($params->is_subs) && $params->is_subs > 0)
			$query->andwhere("is_subs = " . $params->is_subs);

		if (isset($params->house_type) && $params->house_type){
			switch ($params->house_type) {
				case 'xinfang'://新房
					$params->cate_id = self::CATE_HOUSE_NEW;
					break;
				
				case 'ershoufang'://二手房
					$params->cate_id = self::CATE_HOUSE_SECO;
					break;

				case 'zufang'://租房
					$params->cate_id = self::CATE_HOUSE_RENT;
					break;

				case 'xiezilou'://写字楼
					$params->cate_id = self::CATE_HOUSE_OFFI;
					break;

				case 'shangpu'://商铺
					$params->cate_id = self::CATE_HOUSE_SHOP;
					break;

				default:
					NULL;
					break;
			}
		}

		if (isset($params->cate_id) && $params->cate_id > 0)
			$query->andwhere("cate_id = " . $params->cate_id);


		$data = $query->execute()->toArray();

		//获取无限极分类树
		$cate = new \App\Util\Category($data);
		$arr = $cate::tree('children');
		$city = $params->city;
		$city_id = $params->city_id;

		foreach ($arr as $key => $value) {
			if (!isset($arr[$key]["children"])){
				$arr[$key]["children"] =[];
			}else{
				$arr[$key]["children"] = array_values($value["children"]);
			}
		}

		if (!$city && !$city_id)
			return $arr;

		//通过id查询city
		if ($city_id){
			$city = EwDics::findFirst(["columns" => 'id,name,pid,IFNULL(dics_type,"other") AS dics_type', "conditions" => "id = ".$city_id]);
		}else if (preg_match("/(.*)?[省|市|区|县]+$/", $city)){//判断最后一位地级
			$city = mb_substr($city,0,mb_strlen($city)-1,"utf-8"); 
			$where['city'] = $city;
			//查询city
			$city = EwDics::findFirst(["columns" => 'id,name,pid,IFNULL(dics_type,"other") AS dics_type', "conditions" => "name LIKE '%" . $where['city'] . "%' AND pid = 1"]);
		}

		if (is_object($city)){//获取城市区域
			$citys = (array)$city;
			$citys["children"] = EwDics::find(["columns"=>'id,name,pid,IFNULL(dics_type,"other") AS dics_type',
				"conditions" => "cate_id = -1 AND pid = " . $city->id . ' AND is_display = ' .self::DISPLAY_TRUE . ' AND is_del = ' . self::DEL_FALSE,
				"order" => "order_by DESC"])->toArray();
			$arr['0'] = $citys;
		}

		if (is_object($city)){//获取城市特色
			$unique = [];
			$unique['name'] = '特色';
			$unique['id'] = 5;
			$unique['pid'] = 0;
			$unique['dics_type'] = 'feature';
			$unique["children"] = EwDics::find(["columns"=>'id,name,pid,IFNULL(dics_type,"other") AS dics_type',"conditions" => "cate_id = -2 AND pid = " . $city->id, "order" => "order_by DESC"])->toArray();
			$arr[] = $unique;
		}
		ksort($arr);
		return array_values($arr);
	}
	
	/**
	 * [getGroup 获取城市分组按首字母]
	 * @param  [type] $params [description]
	 * @return [type]         [description]
	 */
	public static function getGroup($params, $region = FALSE)
	{

		//通过城市pid 获取城市区域(默认传地区 1 ) 二级联调
		if (isset($params->id) && $params->id && $region)
			return EwDics::query()
				->columns(['id,name as city,lon,lat'])
				->where(" is_display = " .self::DISPLAY_TRUE . " AND is_del = " .self::DEL_FALSE . " AND pid = " . $params->id . " AND cate_id = -1")
				->execute();

		//通过城市名称搜索城市
		if (isset($params->city) && $params->city){
			
			$params->city = preg_match('/市$/', $params->city) ? mb_substr($params->city, 0, -1,"UTF-8") : $params->city;
			return EwDics::query()
				->columns(['id,name as city,lon,lat'])
				->where("name LIKE '%" . $params->city . "%' AND is_display = " .self::DISPLAY_TRUE . " AND is_del = " .self::DEL_FALSE . " AND pid = 1")
				->execute(); 
		}
		
		//搜索热门城市
		if (isset($params->is_hot) && $params->is_hot >= 0)
			return EwDics::query()
				->columns(['id,name as city,lon,lat'])
				->where("is_hot = " . $params->is_hot . " AND is_display = " .self::DISPLAY_TRUE . " AND is_del = " .self::DEL_FALSE . " AND pid = 1")
				->execute();
		
		//获取城市列表		
		$citys = EwDics::find(["columns"=>"id,name as city,pinyin,lon,lat","conditions" =>"is_display = " .self::DISPLAY_TRUE . " AND is_del = " .self::DEL_FALSE . " AND pid = 1"])->toArray();
		$Pinyin = new \App\Util\ChinesePinyin;

		$arr = [];
		//不分组 通过汉字获取首字母
		if (isset($params->is_group) && $params->is_group == -1){
			foreach ($citys as $key => $value) {
				// $pinyin = $Pinyin->TransformUcwords($value['city']);
				$letter = substr($value['pinyin'], 0, 1);
				unset($value['pinyin']);
				$value["first"] = strtolower($letter);
				$arr[$key] = $value;
			}
		}else{//按首字母 分组 
			foreach ($citys as $key => $value) {
				// $pinyin = $Pinyin->TransformUcwords($value['city']);
				$letter = substr($value['pinyin'], 0, 1);
				unset($value['pinyin']);
				$letter = strtolower($letter);
				$arr[$letter][] = $value; 
			}
		}
		ksort($arr);
		return $arr;
	}

	/**
	 * [display 上架]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function display($id)
	{
		if (isset($id) && $id)
			$data = EwDics::findFirst($id);

		if ($data){
			$data->is_display = $data->is_display ? self::DISPLAY_FALSE : self::DISPLAY_TRUE;
			return $data->save();
		}

		return NULL;
	}

	/**
	 * [delete 移除/恢复数据]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function delete($id)
	{
		if (isset($id) && $id)
			$data = EwDics::findFirst($id);

		if ($data){
			$data->is_del = $data->is_del ? self::DEL_FALSE : self::DEL_TRUE;
			return $data->save();
		}

		return NULL;		
	}

	/**
	 * [delete 彻底删除数据 不能删除系统配置]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function forever($id)
	{
		if (isset($id) && $id)
			$row = EwDics::findFirst($id);

		if ($row && $row->is_conf == 0)
			return $row->delete();

		return NULL;
	}

	/**
	 * [save 保存]
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	public static function save($data)
	{

		$row = new EwDics;
		if (isset($data->id) && $data->id)
			$row = EwDics::findFirst($data->id);

		return $row->save((array)$data);
	}

	/**
	 * [saveCity 保存城市]
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	public static function saveCity($data)
	{
		$raw = new \stdClass();

		$raw->name = $data->name;
		$raw->pid  = $data->pid;
		$raw->pid  = $raw->pid ? $raw->pid : 1;
		$raw->is_hot   = $data->is_hot;
		$raw->order_by = $data->order_by;
		$raw->is_display = $data->is_display;
		$raw->cate_id  = self::CATE_AREA;
		$raw->is_subs  = 0;
		$raw->is_multi = 0;
		$raw->is_conf  = 0;
		$raw->is_del   = 0;

		self::save($raw);
	}

	/**
	 * [saveUnique 保存城市特色]
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	public static function saveUnique($data)
	{
		$raw = new \stdClass();

		$raw->name = $data->name;
		$raw->pid  = $data->pid;
		$raw->pid  = $raw->pid ? $raw->pid : 1;
		$raw->order_by = $data->order_by;
		$raw->is_display = $data->is_display;
		$raw->is_hot   = 0;
		$raw->cate_id  = self::CATE_UNIQUE;
		$raw->is_subs  = 0;
		$raw->is_multi = 0;
		$raw->is_conf  = 0;
		$raw->is_del   = 0;

		self::save($raw);
	}
}
